package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.WeChatConstants;
import com.zzyl.properties.WeChatProperties;
import com.zzyl.service.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 获取openid
     *
     * @param code 登录凭证
     * @return
     */
    @Override
    public String getOpenid(String code) {

        //封装参数
        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", weChatProperties.getAppid());
        requestUrlParam.put("secret", weChatProperties.getSecret());
        requestUrlParam.put("js_code", code);

        String result = HttpUtil.get(WeChatConstants.WX_LOGIN_URL, requestUrlParam);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 若code不正确，则获取不到openid，响应失败
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");
    }


    /**
     * 获取手机号
     *
     * @param code 手机号凭证
     * @return
     */
    @Override
    public String getPhone(String code) {

        //获取access_token
        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", weChatProperties.getAppid());
        requestUrlParam.put("secret", weChatProperties.getSecret());

        String result = HttpUtil.get(WeChatConstants.WX_TOKEN_URL, requestUrlParam);
        //解析
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //如果code不正确，则失败
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        String token = jsonObject.getStr("access_token");

        //拼接请求路径
        String url = WeChatConstants.WX_PHONE_URL + token;

        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        result = HttpUtil.post(url, JSONUtil.toJsonStr(param));
        jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") != 0) {
            //若code不正确，则获取不到phone，响应失败
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");
    }

}